<?php

use app\enum\ErrorCode;

/**
 * Here is your custom functions.
 */

function apiSuccess( $data = [] ,$msg = 'ok')
{
    $res = [
        'code' => ErrorCode::SUCCESS,
        'msg'  => $msg,
    ];
    if ($data) {
        $res['data'] = $data;
    }
    return $res;
}

function apiError(string $msg,  $data = [], array $trace = [])
{
    $res = [
        'code' => ErrorCode::ERROR,
        'msg'  => $msg,
    ];
    if ($data) {
        $res['data'] = $data;
    }
    if ($trace) {
        $res['trace'] = $trace;
    }
    return $res;
}

//异常处理
function apiErrorException(int $code,string $msg, array $data = [], array $trace = [])
{
    $res = [
        'code' => $code,
        'msg'  => $msg,
    ];
    if ($data) {
        $res['data'] = $data;
    }
    if ($trace) {
        $res['trace'] = $trace;
    }
    return $res;
}


function mergeImages($image1Path, $image2Path, $outputPath = 'output.jpg') {
    // 加载图片
    $img1 = imagecreatefromstring(file_get_contents($image1Path));
    $img2 = imagecreatefromstring(file_get_contents($image2Path));


    if (!$img1 || !$img2) {
        throw new \Exception('图片加载失败，可能是 URL 不存在或图片格式不正确');
    }

    // 获取宽高
    $width1 = imagesx($img1);
    $height1 = imagesy($img1);
    $width2 = imagesx($img2);
    $height2 = imagesy($img2);

    // 拼接图像宽高（横向拼接）
    $totalWidth = $width1 + $width2;
    $maxHeight = max($height1, $height2);

    // 创建画布
    $mergedImg = imagecreatetruecolor($totalWidth, $maxHeight);

    // 填充背景为白色（可选）
    $white = imagecolorallocate($mergedImg, 255, 255, 255);
    imagefill($mergedImg, 0, 0, $white);

    // 合并两张图
    imagecopy($mergedImg, $img1, 0, 0, 0, 0, $width1, $height1);
    imagecopy($mergedImg, $img2, $width1, 0, 0, 0, $width2, $height2);

    // 保存时判断是否成功
    if (!imagejpeg($mergedImg, $outputPath)) {
        throw new \Exception("保存失败：请检查路径 $outputPath 是否存在或有写入权限");
    }

    // 输出图像（也可使用 imagepng）
    imagejpeg($mergedImg, $outputPath, 90);

    // 释放内存
    imagedestroy($img1);
    imagedestroy($img2);
    imagedestroy($mergedImg);

    echo "合并完成，保存为：$outputPath\n";
    return $outputPath;
}


function uploadToAliyunOss(string $filePath, string $ossKey, array $config = []): string
{

    if (!file_exists($filePath)) {
        throw new \Exception("本地文件不存在：$filePath");
    }
    // 默认配置，可通过 $config 传入覆盖
    $defaultConfig = [
        'accessKeyId'     => 'LTAI5tScCinVjW28MhQY9Qjr',
        'accessKeySecret' => 'Ev9abBgHP0BWSwQXbRwTGwsy3teIqy',
        'endpoint'        => 'oss-cn-beijing.aliyuncs.com',
        'bucket'          => 'hennan-sanjiaomao',
        'cdnDomain'       => 'https://hennan-sanjiaomao.oss-cn-beijing.aliyuncs.com'
    ];
    $config = array_merge($defaultConfig, $config);

    try {
        $ossClient = new \OSS\OssClient(
            $config['accessKeyId'],
            $config['accessKeySecret'],
            $config['endpoint']
        );

        // 上传文件
        $ossClient->uploadFile($config['bucket'], $ossKey, $filePath);

        // 拼接访问 URL
        return rtrim($config['cdnDomain'], '/') . '/' . ltrim($ossKey, '/');
    } catch (\OSS\Core\OssException $e) {
        throw new \Exception("上传到 OSS 失败：" . $e->getMessage());
    }
}
